//
//  HELHomeVC.m
//  sanda
//
//  Created by wsj2015 on 16/7/11.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "HELHomeVC.h"
#import "CSStickyHeaderFlowLayout.h"
#import "HELHomeCollectSectiionHeader.h"
#import "HELHomeCell.h"
#import "HELSearchVC.h"
#import "HospitalInCoureseVC.h"
#import "HELFirstHomeCell.h"
#import "HELNavigationContrller.h"
#import "UISearchBar+VDInnerComponents.h"
#import "JCAlertView.h"
#import "HELCourseDetailVC.h"
#import "MJRefresh.h"
#import "WLReloadPromptView.h"
#import "UIViewController+SQExtension.h"
#import "HELNetworkManager.h"
#import "HELDepartmentModel.h"
#import "UIScrollView+WSJRefresh_MJ.h"
#import "UIImageView+UIActivityIndicatorForSDWebImage.h"
#import "HELGrowHeader.h"



#import "SGScanningQRCodeVC.h"
#import "HELMySignInVC.h"

#import "UINavigationController+WXSTransition.h"
#import "HELMeetingInfo.h"

@interface HELHomeVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UISearchBarDelegate>

@property (nonatomic,  strong) UICollectionView *collectView;

@property (nonatomic,  strong) UIView *courseView;

//@property (nonatomic,  strong) UISearchBar *searchBar;

//@property (nonatomic,  strong) UIView *navCover;

@property (nonatomic,  strong) NSString *bannerImage;

@property (nonatomic,  strong) UIButton *notiBtn;










@end

@implementation HELHomeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestData];
    
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self cwqGetWebData];
  
}

- (void)configUI{
    
    [self titleView:@"首页"];
    
    
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 39, 39);
    [btn setImage:[UIImage imageNamed:@"铃铛"] forState:UIControlStateNormal];
     [btn setImage:[UIImage imageNamed:@"newMessage"] forState:UIControlStateSelected];
    self.notiBtn  = btn;
    [btn addTarget:self action:@selector(messageNot) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *right =[[UIBarButtonItem alloc] initWithCustomView:btn];
    
    
    UIBarButtonItem *right2 =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"搜索"] style:0 target:self action:@selector(gotoSearchVC)];
    UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                   target:nil
                                   action:nil];
    fixedSpace.width = -10;
    self.navigationItem.rightBarButtonItems  =@[fixedSpace,right,right2,];
    
    
    [self.collectView registerNib:[UINib nibWithNibName:@"HELFirstHomeCell" bundle:nil] forCellWithReuseIdentifier:@"HELFirstHomeCell"];
    [self.collectView registerNib:[UINib nibWithNibName:@"HELHomeCell" bundle:nil] forCellWithReuseIdentifier:@"HELHomeCell"];
    [self.collectView registerNib:[UINib nibWithNibName:@"HELHomeCollectSectiionHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HELHomeCollectSectiionHeader"];
    [self.view addSubview:self.collectView];
    [self.collectView registerNib:[UINib nibWithNibName:@"HELGrowHeader" bundle:nil]
       forSupplementaryViewOfKind:CSStickyHeaderParallaxHeader
              withReuseIdentifier:@"HELGrowHeader"];
    UIBarButtonItem *left =[[UIBarButtonItem alloc] initWithImage:nil style:0 target:self action:nil];
    self.navigationItem.leftBarButtonItems =@[left];
//    self.navigationItem.titleView = self.searchBar;
    
    UIBarButtonItem *menuBtn =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ico_camera_7_gray"] style:UIBarButtonItemStyleDone target:self action:@selector(menuAction)];
    self.navigationItem.leftBarButtonItem = menuBtn;
    defineWeakSelf;

    
   [self.collectView wsj_HeaderRefreshBlock:^{
        [weakSelf requestData];
   }];
  

 
    
    
}

#pragma mark -二维码扫描
-(void)menuAction{
    
//    [self.navigationController wxs_pushViewController:[HELSignInVC new] animationType:WXSTransitionAnimationTypeBrickOpenVertical];
  
    
    SGScanningQRCodeVC *scan =[[SGScanningQRCodeVC alloc] init];
    
    weakSelf_define;
    scan.callback  =^(NSString *qrcode){
        
        HELMySignInVC *vc = [HELMySignInVC new];
        vc.courseId = qrcode;
        
        [weakSelf.navigationController pushViewController:vc animated:YES];
//        [weakSelf.navigationController wxs_pushViewController:[HELMySignInVC new] makeTransition:^(WXSTransitionProperty *transition) {
//            transition.animationType = WXSTransitionAnimationTypeBrickOpenVertical;
//            transition.isSysBackAnimation = NO;
//            transition.backGestureType = 0;
//        }];
//    
    };
    HELNavigationContrller *nav = [[HELNavigationContrller alloc] initWithRootViewController:scan];
    
    [self wxs_presentViewController:nav animationType:WXSTransitionAnimationTypeSysCubeFromLeft completion:nil];

    
    

}

- (void)gotoSearchVC{

    HELSearchVC *vc =[HELSearchVC new];
    [self.navigationController pushViewController:vc animated:YES];

}
#pragma mark -请求通知

- (void)cwqGetWebData {
    
    if (!HEL_USERID) {
        return;
    }
    defineWeakSelf;
    /*
     *获取角标
     */
    NSDictionary *param = @{@"userId":HEL_USERID};
    [[HELNetworkManager sharedMg] GET:helStatusBagueUrl parameters:param success:^(id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            cwqHudRequestError(responseObject[@"exception"]);
        }else {
            if ([responseObject count] > 0) {
//                weakSelf.badgeDcit = responseObject[0];
                NSArray *resaArr = responseObject;
                NSDictionary *dict = resaArr.lastObject;
                if ([dict[@"noticeUnRead"] integerValue] >0) {
                    weakSelf.notiBtn.selected = YES;
                }else{
                weakSelf.notiBtn.selected = NO;
                }
                
            }
        }
      
    } failure:^(NSString *err) {
        cwqHudRequestError(err);
       
    }];
    
}

#pragma mark -请求数据...
- (void)requestData{
  
  defineWeakSelf;
   
    NSString *hospitalId = [HELAppManager userInfo].hospitalId;
    if (!hospitalId) {
       
        [JCAlertView showOneButtonWithTitle:@"提示" Message:@"该用户不属于任何医院..." ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"确定" Click:nil];
        return;
    }
    [[HELNetworkManager sharedMg] GET:kHomeData_url parameters:@{@"hospitalId":[HELAppManager userInfo].hospitalId} success:^(NSDictionary *responseObject) {
     
      [weakSelf.dataArray removeAllObjects];
        
        if (responseObject[@"bannerImage"]) {
            weakSelf.bannerImage = responseObject[@"bannerImage"];
        }
        
      if ([responseObject[@"departments"] isKindOfClass:[NSArray class]]) {
        weakSelf.dataArray = [HELDepartmentModel mj_objectArrayWithKeyValuesArray:responseObject[@"departments"]];
      }
        if ([responseObject[@"recommend"] isKindOfClass:[NSArray class]]) {
          
            HELDepartmentModel *recommend =[HELDepartmentModel new];
            recommend.departmentName =@"最新课程";
            recommend.studyDataArray =[HELStudyDataModel mj_objectArrayWithKeyValuesArray:responseObject[@"recommend"]];
            [weakSelf.dataArray addObject:recommend];

        }
       [weakSelf.collectView.header endRefreshing];
       [weakSelf.collectView reloadData];
  } failure:^(NSString *err) {
      [weakSelf.collectView.header endRefreshing];
  }];
    
}


- (void)messageNot{
    HELMeetingInfo *meetingInfoVC = [HELMeetingInfo new];
    meetingInfoVC.title = @"会议信息";
    [self.navigationController pushViewController:meetingInfoVC animated:YES];
 
}





#pragma mark -当行覆盖视图
//- (UIView *)navCover{
//    if (!_navCover) {
//        _navCover = [UIView new];
//        _navCover.backgroundColor  = HexRGB_WSJ(252, 79, 72);
//        _navCover.frame = CGRectMake(0, 0, kScreenWidth, 64);
//        [self.navigationController.navigationBar addSubview:_navCover];
//        
//    }
//    return _navCover;
//}

//- (UISearchBar *)searchBar{
//    if (!_searchBar) {
//        _searchBar =[[UISearchBar alloc] init];
//        _searchBar.frame = CGRectMake(0, 0, kScreenWidth- 100, 33);
//        _searchBar.placeholder = @"搜索平台资料";
//        _searchBar.delegate = self;
//        _searchBar.translucent = YES;
//        _searchBar.searchBarStyle = UIBarStyleBlackTranslucent;
//        _searchBar.tintColor = [UIColor whiteColor];
//        
//        UITextField *tf =[_searchBar vd_inputTextField];
//        tf.layer.borderWidth = 1;
//        tf.layer.borderColor = [UIColor whiteColor].CGColor;
//        tf.textColor = [UIColor whiteColor];
//        tf.layer.cornerRadius = 14;
//        tf.layer.masksToBounds = YES;
//        tf.textColor =[UIColor whiteColor];
//        [tf setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
//        
//    }
//    return _searchBar;
//}
//- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
//{
//    HELSearchVC *vc =[HELSearchVC new];
//    [self.navigationController pushViewController:vc animated:YES];
//
//    return NO;
//}



//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    [self.searchBar endEditing:YES];
//}
- (UIView *)courseView{
    if (!_courseView) {
        _courseView = [[UIView alloc] init];
    }
    return _courseView;
}
- (UICollectionView *)collectView{
    if (!_collectView) {
      
       CSStickyHeaderFlowLayout *layout =[[CSStickyHeaderFlowLayout alloc]init];

        
//        if ([layout isKindOfClass:[CSStickyHeaderFlowLayout class]]) {
            layout.parallaxHeaderReferenceSize = CGSizeMake(self.view.frame.size.width, kScreenWidth *.544);
        layout.parallaxHeaderMinimumReferenceSize = CGSizeMake(kScreenWidth, kScreenWidth *.544);
            layout.itemSize = CGSizeMake(self.view.frame.size.width, layout.itemSize.height);
            // If we want to disable the sticky header effect
            layout.disableStickyHeaders = NO;
//        }


        CGFloat space = 8;
   
        layout.sectionInset =UIEdgeInsetsMake(4, space, 2, space );
        layout.minimumInteritemSpacing = 4;
        layout.minimumLineSpacing = 6;
        CGRect frame =CGRectMake(0, 0, kScreenWidth, kScreenHeight -115);
        _collectView =[[UICollectionView alloc]initWithFrame:frame collectionViewLayout:layout];
        _collectView.delegate = self;
        _collectView.dataSource = self;
        _collectView.showsVerticalScrollIndicator = NO;
        _collectView.alwaysBounceVertical =YES;
        _collectView.backgroundColor = kAppBg;
        if ([_collectView respondsToSelector:@selector(setPrefetchingEnabled:)]) {
            _collectView.prefetchingEnabled = NO;
        }
//
      

    }
    return _collectView;
   
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    HospitalInCoureseVC *vc =[HospitalInCoureseVC new];
//    [self.navigationController pushViewController:vc animated:YES];
      HELCourseDetailVC *vc = [HELCourseDetailVC new];
    HELDepartmentModel *department = self.dataArray[indexPath.section];
    HELStudyDataModel *model =department.studyDataArray[indexPath.row];
    vc.courseId = [model.id integerValue];
     [self.navigationController pushViewController:vc animated:YES];
  
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
   
    
        //适配屏幕
        CGFloat w = (kScreenWidth -24)/3;
        CGFloat h =120;

        if (kScreenWidth == 320 && kScreenHeight ==480) {//iphone4
             h =120;
        }else if(kScreenWidth == 320 && kScreenHeight ==568){ //iphone 5
             h =120;
        }else if(kScreenWidth == 375 && kScreenHeight == 667){ //iphone 6
             h =126;
        }else if(kScreenWidth == 414 && kScreenHeight == 736){ //iphone 6P
             h =136;
        }
        
        return CGSizeMake(w, h);
    
    
    
}
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
//
//
//
//}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    
    
    return CGSizeMake(kScreenWidth, 33);
   
}
#pragma mark UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
//    return [self.dataArray count];
    return self.dataArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

  
    HELDepartmentModel *model =self.dataArray[section];
    return model.studyDataArray.count;
   
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
//    weakSelf_define;
//    NSDictionary *obj = self.dataArray[indexPath.section];
//    if (indexPath.section ==0) {
//        HELFirstHomeCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"HELFirstHomeCell"
//                                                                          forIndexPath:indexPath];
//        cell.clickBlock = ^(NSInteger index){
//            [weakSelf goIntoCourseVC:index indexPath:indexPath];
//        };
//        return cell;
//    }
//    
    HELHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HELHomeCell"
                                                             forIndexPath:indexPath];
//
//    cell.textLabel.text = [[obj allValues] firstObject];
    HELDepartmentModel *model =self.dataArray[indexPath.section];
    HELStudyDataModel *sduty =model.studyDataArray[indexPath.row];
    cell.model = sduty;
    
    return cell;
}
#pragma mark -进入课程

//- (void)goIntoCourseVC:(NSInteger)courseType indexPath:(NSIndexPath *)indexPath{
//    
//    
//    //院内课程
//    if (courseType == 0) {
//        HELSearchVC *vc= [HELSearchVC new];
//        vc.HELSearchVCType = HELSearchVCCouresType_hospitalIn;
//       
//        [self.navigationController pushViewController:vc animated:YES];
//        
//    }
//    //公开课程 学会课程
//   
//    if (courseType ==1) {
//        [self.navigationController pushViewController:[HELVedioAndCourseControllVC new] animated:YES];
//    }
//    
//    if (courseType == 2) {
//        [JCAlertView showOneButtonWithTitle:@"提示" Message:@"本功能暂未开放~" ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"确定" Click:nil];
//        return;
//    }
//    
//    // 点击more的时候
//    if (courseType == -1) {
//        HELSearchVC *vc= [HELSearchVC new];
//        vc.departmentModel = self.dataArray[indexPath.section-1];
//        [self.navigationController pushViewController:vc animated:YES];
//    }
//   
//}


//cell的最小行间距
//
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
//    
//    return 4;
//
//}
//
//
//
////cell的最小列间距
//
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
//    return 8;
//}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
//        NSDictionary *obj = self.dataArray[indexPath.section];
        
        HELHomeCollectSectiionHeader *cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                   withReuseIdentifier:@"HELHomeCollectSectiionHeader"
                                                                          forIndexPath:indexPath];
        HELDepartmentModel *model =self.dataArray[indexPath.section];
        cell.titleL.text =model.departmentName;
        if ([model.departmentName isEqualToString:@"最新课程"]) {
            cell.moreBtn.hidden = YES;
        }else{
            defineWeakSelf;
             cell.moreBtn.hidden = NO;
            cell.getMoreBlock = ^(){
                HELSearchVC *vc= [HELSearchVC new];
                vc.HELSearchVCType = 1;
                vc.departmentModel = self.dataArray[indexPath.section];
                [weakSelf.navigationController pushViewController:vc animated:YES];
                
            };
        
        }
     
        
        return cell;
    } else if ([kind isEqualToString:CSStickyHeaderParallaxHeader]) {
        HELGrowHeader *cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                            withReuseIdentifier:@"HELGrowHeader"
                                                                                   forIndexPath:indexPath];

        if (self.bannerImage) {
           
            [cell.headerPic setImageWithURL:[NSURL URLWithString:self.bannerImage] placeholderImage:[UIImage imageNamed:@"暂无图片.jpg"]usingActivityIndicatorStyle:1];
        }
     
        return cell;
    }
    return nil;
}



//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    
//    if (self.noNeedChangeNavbar ==YES) {
//        return;
//    }
//    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
//    [self navigationBarGradualChangeWithScrollView:scrollView titleView:nil movableView:nil offset:100 color:kMainColor];
//}

@end
